package com.youlu.campus.service.course.convert;

import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.PlatformConfig;
import com.youlu.campus.entity.course.ActivityCourse;
import com.youlu.campus.entity.course.ActivityCourseVideo;
import com.youlu.campus.entity.course.entity.CourseSimpleActivityEntity;
import com.youlu.campus.entity.course.vo.ActivityResultVo;
import com.youlu.campus.entity.course.vo.CourseInfoVo;
import com.youlu.campus.entity.course.vo.CourseVideoVo;
import com.youlu.campus.entity.course.vo.RegisterActivityDetailVo;
import com.youlu.campus.entity.domain.CsInfoDomain;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityTaskService;
import com.youlu.campus.service.activity.UserParticipateActivityInfoService;
import com.youlu.campus.service.course.UserActivityService;
import com.youlu.campus.service.platform.PlatformConfigService;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @author : [dengbo]
 * @className : LiteHomeCourseConvert
 * @description : [描述说明该类的功能]
 * @createTime : [2022/5/17 18:39]
 */
@Component
@Slf4j
public class LiteHomeCourseConvert {
    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private PlatformConfigService configService;

    @Autowired
    private UserActivityService userActivityService;

    @Autowired
    private ActivityTaskService activityTaskService;

    @Autowired
    private UserParticipateActivityInfoService userParticipateActivityInfoService;


    public CourseInfoVo activityCourseDTOToCourse(CourseSimpleActivityEntity activityInfo, ActivityCourse course, List<ActivityCourseVideo> videoList) {
        CourseInfoVo courseVideoVo = new CourseInfoVo();
        courseVideoVo.setActivityId(activityInfo.getId());
        courseVideoVo.setCourseId(course.getId());
        courseVideoVo.setCourseName(course.getName());
        courseVideoVo.setCourseDescription(course.getDescription());
        courseVideoVo.setCentPrice(course.getPrice());
        courseVideoVo.setStartTime(activityInfo.getStartTime());
        courseVideoVo.setEndTime(activityInfo.getEndTime());
        courseVideoVo.setHeadImageUrl(course.getHeadImageUrl());
        courseVideoVo.setCourseType(course.getCourseType());
        courseVideoVo.setShowJoinNum(activityInfo.getShowJoinNum());
        List<CsInfoDomain> list = activityInfo.getCsInfos();
        if (CollectionUtils.isNotEmpty(list)) {
            Optional<CsInfoDomain> domain = list.stream().filter(item -> "wechat".equals(item.getType())).findFirst();
            if (domain.isPresent()) {
                courseVideoVo.setActivityOnlineQrcode(domain.get().getImageUrl());
            }
        }
        courseVideoVo.setHasPaperCa(activityInfo.getHasPaperCa());
        courseVideoVo.setHasElectronicCa(activityInfo.getHasElectronicCa());
        courseVideoVo.setActivityOfficialQrcode(activityInfo.getWxMiniOfficialQrcode());
        BigDecimal price = BigDecimal.valueOf(course.getPrice()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
        courseVideoVo.setPrice(price);
        if (CollectionUtils.isNotEmpty(videoList)) {
            courseVideoVo.setVideoVoList(mapperFacade.mapAsList(videoList, CourseVideoVo.class));
            courseVideoVo.setTotalVideo(videoList.size());

        } else {
            courseVideoVo.setTotalVideo(0);
        }
        if (Objects.nonNull(course.getOriginalPrice())) {
            BigDecimal originalPrice = BigDecimal.valueOf(course.getOriginalPrice()).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
            courseVideoVo.setOriginalPrice(originalPrice);
        }
        // 任务id
        ActivityTaskInfo taskInfo = activityTaskService.find(activityInfo.getId(), TaskBizType.INVITE);
        if (taskInfo != null) {
            courseVideoVo.setTaskId(taskInfo.getId());
        }
        List<ActivityResultVo> activityResultList = simActivityToResultVo(Arrays.asList(activityInfo), true);
        if (CollectionUtils.isNotEmpty(activityResultList)) {
            courseVideoVo.setTotalJoinNum(activityResultList.get(0).getTotalJoinNum());
        }
        return courseVideoVo;
    }

    public CourseVideoVo activityCourseVideoDTOToVideo(ActivityCourseVideo video) {
        return mapperFacade.map(video, CourseVideoVo.class);
    }

    public List<ActivityResultVo> simActivityToResultVo(List<CourseSimpleActivityEntity> list, boolean calculate) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<ActivityResultVo> result = new ArrayList<>();
        boolean hasH5 = false;
        PlatformConfig platformConfig = null;
        for (CourseSimpleActivityEntity entity : list) {
            // 设置
            if ("qimobang-video".equals(entity.getType()) || "video".equals(entity.getType()) || "third-video".equals(entity.getType()) || "recruitment".equals(entity.getType())) {
                result.add(updateJoinNum(entity, mapperFacade.map(entity, ActivityResultVo.class), calculate));
                continue;
            }
            if (hasH5) {
                result.add(updateJoinNum(entity, updeteWechatH5(entity, platformConfig), calculate));

                continue;
            }
            hasH5 = true;
            platformConfig = configService.find();
            result.add(updateJoinNum(entity, updeteWechatH5(entity, platformConfig), calculate));
        }
        return result;
    }

    public ActivityResultVo updateJoinNum(CourseSimpleActivityEntity entity, ActivityResultVo vo, boolean calculate) {
        if (entity.getShowJoinNum() || calculate) {
            Long total = getJoinNum(vo.getId(), entity.getInitJoinNum(), entity.getRandomInitJoinNum(),true);
            log.info("updateJoinNum total:{},InitJoinNum:{},RandomInitJoinNum:{}",total,entity.getInitJoinNum(),entity.getRandomInitJoinNum());
            if (total > 100000) {
                vo.setTotalJoinNum("10万+人已报名");
            } else {
                vo.setTotalJoinNum(total + "人已报名");
            }
        }
        return vo;
    }

    public Long getJoinNum(String activityId, Long initJoinNum, Long randomNum, boolean query) {
        if (query) {
            Long total = initJoinNum + randomNum;
            total += userParticipateActivityInfoService.getJoinedCount(activityId);
            long activityRandomNum = userActivityService.getActivityRandomNum(activityId);
            total += activityRandomNum;
            return total;
        }
        return 0L;
    }

    public ActivityResultVo updeteWechatH5(CourseSimpleActivityEntity entity, PlatformConfig platformConfig) {
        String wechatH5Url = userActivityService.getH5Url(platformConfig, entity);
        ActivityResultVo re = mapperFacade.map(entity, ActivityResultVo.class);
        re.setWechatH5Url(wechatH5Url);
        return re;
    }

    public List<RegisterActivityDetailVo> simActivityToJoinVo(List<CourseSimpleActivityEntity> list) {
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        return mapperFacade.mapAsList(list, RegisterActivityDetailVo.class);
    }
}
